package com.huike.service.impl;

import cn.hutool.crypto.SecureUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.huike.entity.Employee;
import com.huike.mapper.EmpRoleMapper;
import com.huike.mapper.EmployeeMapper;
import com.huike.mapper.RoleMapper;
import com.huike.query.EmployeeQuery;
import com.huike.query.LoginQuery;
import com.huike.service.EmployeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class EmployeeServiceImpl implements EmployeeService {


    @Autowired
    private EmployeeMapper employeeMapper;

    @Autowired
    private EmpRoleMapper empRoleMapper;

    @Override
    public Employee login(LoginQuery lq) {
        Employee dbUser = employeeMapper.getEmployeeByUsername(lq.getUsername());
        if (dbUser==null){
            return null;
        }
        // 判断密码是否正确
        String queryPassword = SecureUtil.md5(lq.getPassword());
        if (queryPassword.equals(dbUser.getPassword())){
            return dbUser;
        }
        return null;
    }

    @Override
    public PageInfo<Employee> getPage(EmployeeQuery eq) {
        PageHelper.startPage(eq.getCurrentPage(),eq.getPageSize());

        List<Employee> all = employeeMapper.getAll(eq);

        return new PageInfo<>(all);
    }

    @Override
    @Transactional
    public void saveOrUpdate(Employee employee,Long[] roleIds) {
        // 密码入库时应该md5
        if (employee.getPassword()!=null){
            employee.setPassword(SecureUtil.md5(employee.getPassword()));
        }

        // 1. 保存或更新employee
        employeeMapper.saveOrUpdate(employee);
        // 2. 删除关于emp关联的角色
        Long empId = employee.getId();
        empRoleMapper.deleteByEmpId(empId);
        // 3. 插入所有新的emp-role关系
        if (roleIds!=null) {
            empRoleMapper.addRelations(empId, roleIds);
        }
    }

    @Override
    public Employee getEmpByID(Integer id) {
        return employeeMapper.getEmpByID(id);
    }

    @Override
    public int deleteById(Long id) {
        return employeeMapper.deleteById(id);
    }
}
